from flask import Flask, render_template, request, send_from_directory, url_for
from flask_socketio import SocketIO, emit
from utils import restful
from flask_avatars import Avatars, Identicon
import os
from hashlib import md5

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

app = Flask(__name__)
app.config['AVATARS_SAVE_PATH'] = os.path.join(BASE_DIR, 'media/avatars')
socketio = SocketIO(app, cors_allowed_origins="*")
avatar = Avatars(app)

online_users = []

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/media/avatars/<path:filename>')
def get_avatar(filename):
    return send_from_directory(app.config['AVATARS_SAVE_PATH'], filename)


# @socketio.on('connect')
# def connect():
#     pass


@socketio.on('disconnect')
def disconnect():
    sid = request.sid
    for user in online_users:
        if user["sid"] == sid:
            online_users.remove(user)
            emit("friend_offline", {"user": user}, broadcast=True)
            break


@socketio.on("login")
def login(data):
    username = data.get("username")
    if not username:
        return restful.params_error('请传入用户名!')
    for user in online_users:
        if user["username"] == username:
            return restful.params_error('此用户已经存在!')
    filenames = Identicon().generate(text=(md5(username.encode('utf-8')).hexdigest()))
    avatar_name = filenames[2]
    avatar_url = url_for('get_avatar', filename=avatar_name)
    user_comment = {"username": username, "avatar": avatar_url, "sid": request.sid, "ip": request.remote_addr}
    users = online_users.copy()
    online_users.append(user_comment)
    emit("friend_online", {"user": user_comment}, broadcast=True)
    return restful.ok(data={"user": user_comment, "online_users": users})


@socketio.on("send_message")
def send_message(data):
    to = data.get("to")
    if not to:
        return restful.params_error('请传入接收者sid!')
    for user in online_users:
        if user["sid"] == to:
            break
    else:
        return restful.params_error('接收者不存在!')
    message = data.get("message")
    if not message:
        return restful.params_error('请传入消息!')
    emit("receive_message", {"from": request.sid, "message": message}, room=[to])
    return restful.ok()


if __name__ == '__main__':
    socketio.run(app)
